package dao

import (
	"context"
	"gorm.io/gorm"
	"mall-admin-go/model"
)

type AdminDao struct {
	*gorm.DB
}

func NewAdminDao(ctx context.Context) *AdminDao {
	return &AdminDao{NewDBCliet(ctx)}
}

func (dao *AdminDao) GetAdminByUsername(name string) (*model.Admin, error) {
	var admin *model.Admin
	err := dao.DB.Model(&model.Admin{}).Where("user_name = ?", name).First(&admin).Error
	return admin, err
}

func (dao *AdminDao) UpdateAdminToken(token, uuid string) error {
	return dao.DB.Model(&model.Admin{}).Where("uuid=?", uuid).Update("token", token).Error
}

func (dao *AdminDao) GetAdmins(conditions map[string]interface{}, page model.BasePage) (admins []*model.Admin, total int64, err error) {
	dao.DB.Model(&model.Admin{}).Where(conditions).Find(&admins).Count(&total)
	if total != 0 {
		err = dao.DB.Model(&model.Admin{}).
			Offset((page.PageNum - 1) * (page.PageSize)).Limit(page.PageSize).
			Where(conditions).Find(&admins).Error
	}
	return
}
func (dao *AdminDao) GetAdminsByDate(conditions map[string]interface{}, page model.BasePage, StartDay, EndDay string) (admins []*model.Admin, total int64, err error) {
	dao.DB.Model(&model.Admin{}).
		Offset((page.PageNum-1)*(page.PageSize)).Limit(page.PageSize).
		Where(conditions).Where("created_at BETWEEN ? AND ?", StartDay, EndDay).Find(&admins).Count(&total)
	if total != 0 {
		err = dao.DB.Model(&model.Admin{}).
			Offset((page.PageNum-1)*(page.PageSize)).Limit(page.PageSize).
			Where(conditions).Where("created_at BETWEEN ? AND ?", StartDay, EndDay).Find(&admins).Error
	}
	return
}
